<template>

    <a-modal :title="relation.title" :width="640" :visible="relation.visible" :confirmLoading="submitLoading" @ok="submitFee('formRelation')" @cancel="closeFee">
        <a-form-model :model="formRelation" ref="formRelation">
            <a-form-model-item label="园区合作协议（支持pdf、文件大小20MB）">
              <a-upload :file-list="fileList" v-model="formRelation.agreement" :customRequest="handleExceed" :before-upload="beforeUpload" :remove="handleUploadRemove">
                <a-button icon="upload">上传合同</a-button>
              </a-upload>
            </a-form-model-item>
            <a-form-model-item label="园区名称（支持模糊查询）" prop="parkId" :rules="[{ required: true, message: '填写园区名称!' }]">
              <a-select v-model="formRelation.parkId"
                showSearch
                allowClear
                placeholder="请输入园区名称关键字"
               :options="parkOptions"
               :filter-option="filterOption">
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="签约日期" prop="signTime" :rules="[{ required: true, message: '选择签约日期!' }]">
              <a-date-picker v-model="formRelation.signTime" style="width: 100%;" placeholder="选择签约日期" value-format="YYYY-MM-DD" />
            </a-form-model-item>
            <a-form-model-item label="失效日期" prop="invalidTime" :rules="[{ required: true, message: '选择失效日期!' }]">
              <a-date-picker v-model="formRelation.invalidTime" style="width: 100%;" placeholder="选择失效日期" value-format="YYYY-MM-DD" />
            </a-form-model-item>
            <a-form-model-item label="服务费扣除方式" prop="serviceFeeSettleMode" :rules="[{ required: true, message: '请选择服务费扣除方式!' }]">
              <a-radio-group v-model:value="formRelation.serviceFeeSettleMode" name="radioGroup">
                <a-radio :value="item.value" v-for="(item,index) in seriverModeData" :key="index">{{item.label}}</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="服务费计算方式" prop="serviceFeeCalculateMode" :rules="[{ required: true, message: '选择计算方式!' }]">
              <a-radio-group v-model:value="formRelation.serviceFeeCalculateMode" name="radioGroup">
                <a-radio :value="item.value" v-for="(item,index) in computeModeData" :key="index">{{item.label}}</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-row :gutter="10" v-for="(domain,index) in formRelation.feeForm" :key="index">
              <a-col :span="6"><!--index >= 1-->
                <a-form-model-item label="服务费开始金额" :prop="`feeForm[${index}].amountStart`" :rules="[{ required: true, message: '填写开始金额!' }]">
                  <a-input-number placeholder="请输入开始金额" :disabled="true" v-model="domain.amountStart" :min="0" :max="100000" :parser="(value)=>{
      let reg = /^(-)*(\d+)\.(\d\d).*$/;
      return value.replace(/\s?|(,*)/g, '').replace(reg,'$1$2.$3');
    }"/>
                </a-form-model-item>
              </a-col> 
              <a-col :span="5" style="position: relative;">
                <a-form-model-item label="服务费区间" :prop="`feeForm[${index}].operator`" :rules="[{ required: true, message: '填写区间!' }]">
                    <a-select placeholder="请输入区间" v-model:value="domain.operator">
                      <a-select-option value="1">包含</a-select-option>
                      <a-select-option value="2">不包含</a-select-option>
                    </a-select>
                </a-form-model-item>
                  <a-popover title="温馨提示">
                    <template #content>
                      <p>如果选择包含，开始金额0-- 结束金额10000，10000会计算在内。如果不包含10000不会计算在内</p>
                    </template>
                   <a-icon type="question-circle" style="position: absolute;top: 11px;right:11px;color: #1a90ff;font-size: 16px;"></a-icon>
                  </a-popover>
              </a-col> 
              <a-col :span="6">
                <a-form-model-item label="服务费结束金额" :prop="`feeForm[${index}].amountEnd`" :rules="[{ required: true, message: '填写结束金额!' },{validator: function(rule,value, callback){return handleAmount(rule,value, callback,index)}}]">
                  <a-input-number placeholder="请输入结束金额" @change="function(val){return amountEndChange(val,index)}" v-model="domain.amountEnd" :min="1" :max="100000" :parser="(value)=>{
      let reg = /^(-)*(\d+)\.(\d\d).*$/;
      return value.replace(/\s?|(,*)/g, '').replace(reg,'$1$2.$3');
    }"/>
                </a-form-model-item>
              </a-col> 
              <a-col :span="5">
                <a-form-model-item label="服务费比例" :prop="`feeForm[${index}].serviceRatio`" :rules="[{ required: true, message: '填写服务费比例!' }]">
                  <a-input-number 
                    placeholder="请输入比例" 
                    v-model="domain.serviceRatio" 
                    :min="0" 
                    :max="100" 
                    :parser="(value)=>{
      let reg = /^(-)*(\d+)\.(\d\d\d\d).*$/;
      return value.replace(/\s?|(,*)/g, '').replace(reg,'$1$2.$3');
    }"
                     />
                </a-form-model-item>
              </a-col> 
              <a-col :span="2" style="padding-top: 40px;">
                <a-button icon="plus-circle" size="large" v-if="index===0" @click="addsFeeForm" type="link"></a-button>
                <a-button icon="minus-circle" size="large" v-if="index !== 0" @click="removeFeeForm(index)" type="link"></a-button>
              </a-col>
            </a-row>
        </a-form-model>
    </a-modal>
</template>

<script>
import store from '@/store'
import { 
    sysBaseUpload
 } from '@/api/manage/base'
 import { 
    computeMode,
    seriverMode
 } from '@/config/baseData'
 import { 
   sysEnterpriseParkFeeConfigAdd,
   sysEnterpriseParkFeeConfigEdit
 } from '@/api/manage/serviceFee'
export default {
  name: 'ServiceRelationForm',
  data () {
    return {
      relation:{
        id:'',
        title:'设置关联关系',
        visible:false,
        fetching:false
      },
      fileList:[],
      parkOptions:[],
      computeModeData:computeMode,
      seriverModeData:seriverMode,
      formRelation:{
        agreement:'',
        signTime:'',
        invalidTime:'',
        parkId:'',
        serviceFeeCalculateMode:'',
        serviceFeeSettleMode:'',
        enterpriseId:'',
        feeForm:[
          {
            amountStart: 0,
            amountEnd:'',
            operator:'',
            serviceRatio:''
          }
        ]
      },
      flag:true,
      submitLoading:false
    }
  },
  methods: {
    async add(item,flag){
      const {formRelation} = this;
      this.parkOptions = await store.dispatch('getSysAllParkEnable');
      this.flag = flag;
      this.fileList = [];
      if(flag === true){
        for(var keys in formRelation){
          formRelation[keys] = '';
        }
        this.formRelation.feeForm = [
          {
            amountStart: 0,
            amountEnd:'',
            operator:'',
            serviceRatio:''
          }
        ]
      }else{
        this.formRelation.feeForm = [];
        for(var keys in item){
          formRelation[keys] = item[keys];
        }
        if(item.fees){
          item.fees.forEach(v=>{
            v.operator = v.operator === '<=' ? '1':'2';
          })
          this.formRelation.feeForm = item.fees;
        }
        if(item.agreement){
          var fileName =item.agreement.substring(item.agreement.lastIndexOf('/')+1)
          let file = {name:fileName,url:item.agreement,uid:item.enterpriseId}
          this.fileList.push(file)
        }
      }
      this.formRelation.enterpriseId = item.enterpriseId;
      this.relation.visible = true;
    },
    filterOption(inputValue,option){
      return option.componentOptions.children[0].text.toLowerCase().indexOf(inputValue) >= 0
    },
    async handleExceed(file, fileList) {
      let formData = new FormData();
      formData.append("file",file.file);
      let {code,data} = await sysBaseUpload(formData);
      if(code === '1'){
        this.fileList = [];
        this.formRelation.agreement = data;
        file.file.url = data;
        this.fileList.push(file.file);
      }
    },
    beforeUpload(file, fileList) {
      const isJpgOrPng = file.type === 'application/pdf'
      if (!isJpgOrPng) {
        this.$message.error('只支持pdf格式!')
      }
      const isLt1M = file.size / 1024 / 1024 < 20
      if (!isLt1M) {
        this.$message.error('文件大小不得大于20MB!')
      }
      return isJpgOrPng && isLt1M

    },
    amountEndChange(val,index){
      const feeLen = this.formRelation.feeForm.length;
      if(index !== feeLen-1){
        this.formRelation.feeForm[index+1].amountStart = val;
      }
    },
    handleUploadRemove(file){
       this.formRelation.agreement = '';
        this.fileList.splice(0,1);
    },
    addsFeeForm(){
      const feeFormArr = this.formRelation.feeForm;
      for(var i=0;i<feeFormArr.length;i++){
         if(!feeFormArr[i].operator){
          return this.$message.error('请选择服务费区间')
        }
        if(!feeFormArr[i].amountEnd){
          return this.$message.error('请填写结束金额')
        }
        if(!feeFormArr[i].serviceRatio){
          return this.$message.error('请填写服务费比例')
        }
      }
      var feeFormPopData = this.formRelation.feeForm.at(-1);
      
      let params = {
        amountStart: feeFormPopData.amountEnd,
        amountEnd:'',
        operator:'',
        serviceRatio:''
      }
      this.formRelation.feeForm.push(params);
    },
    removeFeeForm(index) {
       this.formRelation.feeForm.splice(index, 1)
    },
    handleAmount(rule,value, callback,index){
      const feeForm = this.formRelation.feeForm[index];
      if (value <= feeForm.amountStart) {
          callback('结束金额必须大于开始金额！');
      }
      callback()
    },
    submitFee(formName){
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const { formRelation } = this;
          let params = {};
          formRelation.feeForm.forEach(v=>{
            v.operator = v.operator === '1' ?'<=':'<';
          })
          params.fees = formRelation.feeForm;
          params.parkId = formRelation.parkId;
          params.enterpriseId = formRelation.enterpriseId;
          params.serviceFeeSettleMode = formRelation.serviceFeeSettleMode;
          params.serviceFeeCalculateMode = formRelation.serviceFeeCalculateMode;
          params.agreement = this.fileList && this.fileList.length >=1 ? this.fileList[0].url : '';
          params.signTime = formRelation.signTime;
          params.invalidTime = formRelation.invalidTime;
          this.submitLoading = true;
          const {code} =  this.flag ? await sysEnterpriseParkFeeConfigAdd(params) : await sysEnterpriseParkFeeConfigEdit(params);
          this.submitLoading = false;
          if(code === '1'){
            this.$message.success('操作成功');
            this.relation.visible = false;
            this.$emit("on-ok",this.flag);
          }
        }else{
          return false;
        }
      });
    },
    closeFee(){
      this.relation.visible = false;
      this.$emit("on-ok",false);
    }
  }
}
</script>

